<template>
    <el-upload :action="url" ref="elUploadRef"
               :on-success="uploadSuccess"
               :on-error="uploadError"
               :on-change="change"
               :on-exceed="onExceed"
               :limit="1"
               :show-file-list="false"
               :data="params"
    >
        <div>
            <el-button type="primary">上传</el-button>
        </div>

        <template #tip>
            <el-alert v-if="data.error!=''" :title="data.error" type="error" :closable="false" />
        </template>

    </el-upload>
    <el-tooltip :content="modelValue" v-if="modelValue!=''">
        <el-button type="success" text size="small" >
            <div class="d_flex flex_jc_sb">
                <span class="flex_1">{{modelValue}}</span>
                <el-icon class="el-icon--right" @click="remove()"><Close /></el-icon>
            </div>
        </el-button>
    </el-tooltip>

</template>

<script setup lang="ts">

import {reactive, ref} from "vue";

const props = withDefaults(defineProps<{
    modelValue?: string,
    url?: string,
    params?: any,
}>(),{
    url:import.meta.env.VITE_APP_UPLOAD_FILE_URL
})

const emits = defineEmits(['update:modelValue', 'onChange'])

const data = reactive({
    error: ''
})
const elUploadRef:any = ref()


const uploadSuccess = (res: any, file:any) => {

    if (res.error == 0) {
        emits("update:modelValue", res.url)
        data.error = ''    // 清空错误信息
    } else {
        data.error = res.msg
        elUploadRef.value.handleRemove(file)
    }
}

const uploadError = (res:any) => {
    data.error = "上传失败"
}

const onExceed = () => {
    data.error = '只能上传一个文件，请删除后再上传'
}

const change = (file:any,fileList:any) => {
    emits("onChange", file, fileList)
}

const remove = () => {
    elUploadRef.value.clearFiles()
    emits("update:modelValue", '')
    data.error = ''
}

</script>

<style scoped>
</style>